const http = require('https')
const iconv = require('iconv-lite')
const cheerio = require('cheerio')
const fs = require('fs')
const path = require('path')

const EventEmitter = require('events')



class GirlSpider extends EventEmitter {
    //下载html
    getHtml() {
        http.get(`https://www.2717.com/ent/meinvtupian/list_11_2.html`, (res) => {
            let data = []

            res.on('data', chunk => {
                data.push(chunk)
            })
            res.on('end', () => {
                var html = iconv.decode(Buffer.concat(data), 'gbk')
                
                this.emit('getHtmlFinish',html)
            })
        })

    }

    extraDataFromHtml(html) {
        let $ = cheerio.load(html)
        let imgData = []
        let arr = $('div.MeinvTuPianBox>ul>li>a>i>img').toArray()
        for (let i = 0; i < arr.length; i++) {
            let obj = arr[i]
            let src = $(obj).attr('src')
            let title = $(obj).attr('alt')
            imgData.push({
                src, title
            })
        }
        this.emit('extraDataFinish',imgData)
    }
    
    downloadImage(imgData) {
        imgData.forEach(item => {
            http.get(item.src, res => {
                let imgPath=path.join('imgs', item.title + path.extname(item.src))
                let writer = fs.createWriteStream(imgPath)
                res.pipe(writer)
            })
        })
    }

    start(){
        this.on('getHtmlFinish',html=>{
            this.extraDataFromHtml(html)
        })
        this.on('extraDataFinish',imgData=>{
            this.downloadImage(imgData)
        })
        this.getHtml()
    }

}


let girlSpider=new GirlSpider()
girlSpider.start()




